//
//  ZSCreationResultsViewController.swift
//  creativeassistant
//
//  Created by Lazy on 2025/2/12.
//

import UIKit
import ProgressHUD

class ZSCreationResultsViewController: ZSBaseViewController {
    
    var template: String = ""
    var content: String = ""
    
    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var contentLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hexString: "#F0F3FD")
        navigationHeight.constant = UIApplication.shared.statusBarFrame.size.height + 44
        contentLabel.text = content
    }

    @IBAction func goBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func copyContent(_ sender: UIButton) {
        if let content = contentLabel.text {
            UIPasteboard.general.string = content
            self.view.makeToast("复制成功", position: .center)
        }
    }
    
    @IBAction func regenerate(_ sender: UIButton) {
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbmajiabao/api/wenxinyiyan/chat"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
        let parameters: [String: Any] = [
            "messages": [
                [
                    "role": "user",
                    "content": template
                ]
            ]
        ]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            if let error = error {
                self.view.makeToast("创作失败，请重试！", duration: 1.0, position: .center)
                return
            }
            guard let data = data else {
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let dict = json["data"] as? [String: Any], let result = dict["result"] as? String, !result.isEmpty {
                    DispatchQueue.main.async {
                        self.contentLabel.text = result
                    }
                }
            } catch {
                self.view.makeToast("创作失败，请重试！", duration: 1.0, position: .center)
            }
        }
        task.resume()
    }
    
}
